<script lang="ts" setup>
import { useToggle } from '@vueuse/core'

import { useClassForm } from './composables/useClassForm'
import { type TeacherOption, useTeacher } from './composables/useTeacher'
import CourseTable from './CourseTable.vue'
import { useArcoForm } from '@/composables/useArcoForm'
import type { FormRule } from '@/types/components-tool'

const [visible, toggleVisible] = useToggle()
const { isPending, submit } = useClassForm(toggleVisible)
const { user, notDisable, isSearching, teachers, teacherFilter } = useTeacher(visible)
const { formRef, formState, onValidateSuccess, validate } = useArcoForm({
  name: '',
  description: '',
  courseID: 1,
  teacher: user.value.username
})

onValidateSuccess(submit)

const rules: FormRule<typeof formState.value> = {
  name: [{ required: true, message: '请输入班级名称' }],
  teacher: [{ required: true, message: '请选择任课教师' }],
  courseID: [{ required: true, message: '请选择课程' }],
  description: [{ required: true, message: '请输入班级概述' }]
}
</script>

<template>
  <a-button status="success" type="dashed" size="mini" @click="toggleVisible(true)">
    创建班级
    <a-modal
      hide-title
      :modal-style="{ padding: '0', width: '100%', maxWidth: '768px' }"
      :body-style="{ paddingBottom: '0' }"
      :ok-loading="isPending"
      ok-text="创建"
      :visible
      @ok="validate"
      @cancel="toggleVisible(isPending)"
    >
      <a-form ref="formRef" size="small" layout="vertical" :model="formState" :rules>
        <a-form-item field="name" label="班级名称" help="如xx级第二学期xx课程">
          <a-input v-model.trim="formState.name" :max-length="64" show-word-limit />
        </a-form-item>
        <a-form-item field="teacher" label="任课教师" help="非管理员仅可创建自己任教的班级">
          <a-auto-complete
            v-model="formState.teacher"
            :data="teachers"
            :loading="isSearching"
            :disabled="!notDisable"
            :filter-option="teacherFilter"
            placeholder="请输入班级教师工号"
          >
            <template #option="{ data: { label, value } }: { data: TeacherOption }">
              <a-typography-text code>{{ value }}</a-typography-text>
              <span class="text-arco-3 ml-xs">{{ label }}</span>
            </template>
          </a-auto-complete>
        </a-form-item>
        <a-form-item field="description" label="班级概述" help="描述一下班级">
          <a-input v-model.trim="formState.description" :max-length="256" show-word-limit />
        </a-form-item>
        <a-form-item field="selectedCourse" label="选择课程">
          <CourseTable v-model="formState.courseID" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-button>
</template>
